package com.hsogoo.ultraman.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.google.common.io.CharStreams;
import com.hsogoo.ultraman.exceptions.UltramanConfigException;

/**
 * Created by za-huangsaigang on 2018/9/20.
 */
public class HttpUtil {

    private int connectTimeout = 1000; //1 second
    private int readTimeout = 5000; //5 seconds

    public String doGet(String url) {
        InputStreamReader isr = null;
        InputStreamReader esr = null;
        int statusCode;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

            conn.setRequestMethod("GET");

            if (System.getProperty("http.connectTimeout") != null) {
                connectTimeout = Integer.valueOf(System.getProperty("http.connectTimeout"));
            }

            if (System.getProperty("http.readTimeout") != null) {
                readTimeout = Integer.valueOf(System.getProperty("http.readTimeout"));
            }

            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);

            conn.connect();

            statusCode = conn.getResponseCode();
            String response;

            try {
                isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8);
                response = CharStreams.toString(isr);
            } catch (IOException ex) {
                InputStream errorStream = conn.getErrorStream();
                if (errorStream != null) {
                    esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8);
                    try {
                        CharStreams.toString(esr);
                    } catch (IOException ioe) {
                        //ignore
                    }
                }
                throw ex;
            }
            if (statusCode == 200) {
                return response;
            }
        } catch (Throwable ex) {
            throw new UltramanConfigException("Could not complete get operation", ex);
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException ex) {
                    // ignore
                }
            }

            if (esr != null) {
                try {
                    esr.close();
                } catch (IOException ex) {
                    // ignore
                }
            }
        }

        throw new UltramanConfigException(String.format("Get operation failed for %s, code=[%s]", url, statusCode));
    }
}
